<template>
    <fieldset>
        <legend>三级联动</legend>

        省 : <select v-model="sel1" @change="provienceChange(sel1)">
            <option v-for="item in provience" :key="item.id" :value="item.id">{{ item.name }}</option>
        </select>

        市 : <select v-model="sel2" @change="cityChange(sel2)">
            <option v-for="item in city" :key="item.id" :value="item.id">{{ item.name }}</option>
        </select>

        区 : <select v-model="sel3">
            <option v-for="item in town" :key="item.id" :value="item.id">{{ item.name }}</option>
        </select>
    </fieldset>
</template>

<script>
import * as api from "@/api/select"
export default {
    data() {
        return {
            // 省的数据
            provience: [],
            // 选中的省的id
            sel1: 1,
            // 市的数据
            city: [],
            //  选中的市的id
            sel2: 1,
            // 区的数据
            town: [],
            // 选中的区的id
            sel3: ""
        }
    },
    // 获取数据
    mounted() {
        api.fetchData().then(res => {
            console.log(res)
            this.provience = res
            console.log(this.provience)
            // 获取默认第一条的 id
            let p1 = res[0].id
            this.provienceChange(p1)
        })
    },
    methods: {
        // 省变化
        provienceChange(p1) {
            console.log(p1);
            api.fetchCity(p1).then(res => {
                this.city = res;
                console.log(this.city)
                // 默认选中
                let p2 = res[0].id
                this.sel2 = p2;
                this.cityChange(p2)
            })
        },
        // 市变化
        cityChange(p2) {
            console.log(p2)
            api.fetchTown(p2).then(res => {
                this.town = res
                console.log(this.town);
                //默认选中
                if (res.length > 0) {
                    this.sel3 = res[0].id
                }
            })
        }
    }
}



</script>



<style scoped>
select {
    width: 100px;
}
</style>